
// 旗帜Datatable
var flagTable;
var btnAdvSearchflg= false;
var opFlagId = "";
var quickSearch = ""; // 快速查询
/**
 * 页面初始化
 */
$(function () {
    
    // 输入有效性验证
    $("#flagCreateForm , #flagEditForm").validate({
        debug:true,
        errorPlacement: function(error, element)
        {
            error.insertAfter(element);
        }
    });
    
    $.extend($.validator.defaults,{ignore:""}); //隐藏控件也校验，去掉此行不验证隐藏控件
    
    //点击空白处高级查询收起来
    $("body").click(function(e){ 
        if(btnAdvSearchflg==true){
            btnAdvSearchflg = false;
        } else {
            $("#advSearchPanel").hide();
            $("#btnAdvSearch").children("i:eq(0)").removeClass("fa-angle-double-up");
            $("#btnAdvSearch").children("i:eq(0)").addClass("fa-angle-double-down");    
        }
    });
    
    // 高级搜索“提交”按钮点击
    $("#advSearchSubmit").click(function (e) {
        //记录高级查询的检索条件
        setHidValue("frmAdvSearch");
        quickSearch = encodeURI($('#flag_name').val());
        flagTable.draw();
        $("#advSearchPanel").hide();
        $("#btnAdvSearch").children("i:eq(0)").removeClass("fa-angle-double-up");
        $("#btnAdvSearch").children("i:eq(0)").addClass("fa-angle-double-down");
        
    });
    
    // 快速查询
    $("#btnQuickSearch").click(function() {
    	quickSearch = encodeURI($('#quickSearch').val());
    	flagTable.draw();
    });
    
    // 高级搜索 默认隐藏
    $("#advSearchPanel").hide();
    $("#btnAdvSearch").click(function () {
        btnAdvSearchflg = true;
        if ($("#advSearchPanel").is(":hidden")) {
            $("#advSearchPanel").show();
            $(this).children("i:eq(0)").removeClass("fa-angle-double-down");
            $(this).children("i:eq(0)").addClass("fa-angle-double-up");
        } else {
            $("#advSearchPanel").hide();
            $(this).children("i:eq(0)").removeClass("fa-angle-double-up");
            $(this).children("i:eq(0)").addClass("fa-angle-double-down");
        }
        
    });
    $("#advSearchPanel").click(function () {
        btnAdvSearchflg = true;
    })
    
 // 初始化企业列表
    $.ajax({
        type:"GET",
        url:"/enterprise/getUserEnterpriseList.action",
        contentType: "application/json;charset=utf-8",
        dataType: "json",
        async: true,//同步
        success:function(data) {
            if (data.entName) {
                $("#form-enterprise option").remove();
                $("#form-enterprise").append("<option value=''>请选择</option>");
                $.each(data.entName, function (n, value) {
                    $('#form-enterprise').append("<option value='" + value.entId + "'>" + value.entName + "</option>");
                });
                
                $("#form-enterpriseEdit option").remove();
                $("#form-enterpriseEdit").append("<option value=''>请选择</option>");
                $.each(data.entName, function (n, value) {
                    $('#form-enterpriseEdit').append("<option value='" + value.entId + "'>" + value.entName + "</option>");
                });
            } else {
                window.top.window.showModalAlert(data.msg);
            }
        },
        error:function(XMLHttpRequest, textStatus) {
            if (XMLHttpRequest.status == 500) {
                var result = eval("(" + XMLHttpRequest.responseText + ")");
                alert(result.errorObject.errorText);
            }
        }
    });
    
 // 初始化表格控件
    flagTable = $('#flag-table').DataTable({
        "processing": true,
        "serverSide": true,
        "lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]],
        "dom": '<"bottom"rtflp>',
        "searching": false,
        "pagingType": "full_numbers",
        "deferRender": true,
        "ajax": {
            "url": "/flag/flagList.action",
            "data": function ( d ) {
                if ($("#advSearchPanel").is(":hidden")) {
                	d.quickSearch = quickSearch;
                } else {
                    //高级搜索
                    var flag_type = encodeURI($('#flag_type').val());
                    var flag_name = encodeURI($('#flag_name').val());
                    var advData = {
                        "flag_type": flag_type,
                        "flag_name": flag_name
                    };
                    d.formJson = JSON.stringify(advData);
                }
            }
        },
        "tableTools": {
            "sRowSelect": "bootstrap"
        },
        "columns": [{
                "data": "flagTypeName"
            },{
                "data": "flagShow"
            }, {
                "data": "flagName"
            }, {
                "data": "remark"
            }, {
                "data": "operation"
            }
        ],
        "columnDefs": [{
                "orderable":false,
                "targets":[1]
            }, {
                "orderable":false,
                "targets":[4]
            }
        
        ],
        "order": [[ 0, "asc" ],[ 2, "asc" ],[ 3, "asc" ]]
    });
    
    //事件
    // 创建分单规则保存按钮点击事件绑定
    $("#add-flag").click(function(){
        
     // 父窗体归还本页的编辑对话框
        window.top.window.returnCustomModalDialog();
        
        // 输入有效性验证
        if(!$("#flagCreateForm").valid()) {
            // 父窗体借用本页的编辑对话框
            window.top.window.borrowCustomModalDialog($("#create-flag-form"));
            return false;
        }
        //保存分担规则
        var flagType = $("#flagType").val(); 
        var flagName = $("#form-flag-name").val();
        var entId = $("#form-enterprise").val();
        var remark = $("#form-remark").val();
        var color = $("#selected-color1").val();
        
        var params = {};  
        params.flagType = flagType;  
        params.flagName = flagName;  
        params.entId = entId;
        params.remark = remark;
        params.color = color;
        
        var loading = window.top.window.getIndexBusyOverlay();
        $.ajaxSettings['contentType'] = "application/x-www-form-urlencoded; charset=utf-8";
        $.ajax({
        type:"POST",
        url:"/flag/createFlag.action",
        data:JSON.stringify(params),
        contentType: "application/json;charset=utf-8",
        dataType: "json",
        beforeSend:function(){
            if(loading) {
            	loading.settext("正在处理中，请稍后...");
            }
        },
        success:function(data) {
        	loading.remove();
            if (data.success == "Y") {
                $('#create-flag-form').modal('hide');
                window.top.window.showScoMessage('ok', '创建成功');
                flagTable.draw();
            } else{
                window.top.window.showModalAlert(data.errormessage);
                window.top.window.borrowCustomModalDialog($("#create-flag-form"));
            }
        },
        error:function(XMLHttpRequest, textStatus) {
        	loading.remove();
            if (XMLHttpRequest.status == 500) {
                var result = eval("(" + XMLHttpRequest.responseText + ")");
                alert(result.errorObject.errorText);
            }
        }
        });
        
    });
    
 // 创建分单规则保存按钮点击事件绑定
    $("#edit-flag").click(function(){
        
     // 父窗体归还本页的编辑对话框
        window.top.window.returnCustomModalDialog();
        
        // 输入有效性验证
        if(!$("#flagEditForm").valid()) {
            // 父窗体借用本页的编辑对话框
            window.top.window.borrowCustomModalDialog($("#edit-flag-form"));
            return false;
        }
        //保存分担规则
        var flagId = $("#edit-flag-form").attr("flagiD");
        var flagType = $("#flagTypeEdit").val();
        var flagName = $("#form-flag-nameEdit").val();
        var entId = $("#form-enterpriseEdit").val();
        var remark = $("#form-remarkEdit").val();
        var color = $("#selected-color2").val();
        
        var params = {};  
        params.flagType = flagType;  
        params.flagName = flagName;  
        params.entId = entId;
        params.remark = remark;
        params.color = color;
        params.flagId = flagId;
        
        var loading = window.top.window.getIndexBusyOverlay();
        $.ajaxSettings['contentType'] = "application/x-www-form-urlencoded; charset=utf-8";
        $.ajax({
        type:"POST",
        url:"/flag/updateFlag.action",
        data:JSON.stringify(params),
        contentType: "application/json;charset=utf-8",
        dataType: "json",
        //async: false, // 同步
        beforeSend:function(){
            if(loading) {
            	loading.settext("正在处理中，请稍后...");
            }
        },
        success:function(data) {
        	loading.remove();
            if (data.success == "Y") {
                $('#edit-flag-form').modal('hide');
                window.top.window.showScoMessage('ok', '修改成功');
                flagTable.draw();
            } else{
                window.top.window.showModalAlert(data.errormessage);
                window.top.window.borrowCustomModalDialog($("#edit-flag-form"));
            }
        },
        error:function(XMLHttpRequest, textStatus) {
        	loading.remove();
            if (XMLHttpRequest.status == 500) {
                var result = eval("(" + XMLHttpRequest.responseText + ")");
                alert(result.errorObject.errorText);
            }
        }
        });
        
    });
    
    // 创建分单规则对话框关闭事件发生
    $('#create-flag-form').on('hide.bs.modal', function () {
        // 父窗体归还本页的编辑对话框
        window.top.window.returnCustomModalDialog();
    })
    
     // 创建分单规则对话框关闭事件发生
    $('#edit-flag-form').on('hide.bs.modal', function () {
        // 父窗体归还本页的编辑对话框
        window.top.window.returnCustomModalDialog();
    })
});

/**
 * 删除提示
 * @param btnDelete
 * @returns
 */
function operationDelete(btnDelete){
    opFlagId = $(btnDelete).attr("flagid");
    window.top.window.showModalConfirm("确定要删除该旗帜吗？", doDelete);
}

/**
 * 执行删除店铺操作
 * @returns
 */
function doDelete() {
    if (opFlagId == "") {
        return;
    }
    var loading = window.top.window.getIndexBusyOverlay();
    $.ajax({
        type:"POST",
        url:"/flag/deleteFlag.action?flagID=" + opFlagId,
        contentType: "application/json;charset=utf-8",
        dataType: "json",
        //async: false,//同步
        beforeSend:function(){
            if(loading) {
            	loading.settext("正在处理中，请稍后...");
            }
        },
        success:function(data) {
        	loading.remove();
            if (data.success == "Y") {
                window.top.window.showScoMessage('ok', '删除成功');
            } else{
                window.top.window.showModalAlert(data.msg);
            }
            opShopId = "";
            flagTable.draw();
        },
        error:function(XMLHttpRequest, textStatus) {
        	loading.remove();
            if (XMLHttpRequest.status == 500) {
                var result = eval("(" + XMLHttpRequest.responseText + ")");
                alert(result.errorObject.errorText);
            }
        }
    });
}
/**
 * 编辑按钮点击
 * @param btnEdit
 * @returns
 */
function operationEdit(btnEdit) {
    $("#flagEditForm")[0].reset();
    opFlagId = $(btnEdit).attr("flagid");

    // 初始化项目列表
    $.ajax({
        type:"GET",
        url:"/flag/flagDetail.action?flagId=" + opFlagId,
        contentType: "application/json;charset=utf-8",
        dataType: "json",
        async: false,//同步
        success:function(data) {
            if (data.result == "success") {
                $("#edit-flag-form").attr("flagid", opFlagId);
                $("#flagTypeEdit").val(data.data.flagType);
                $("#form-flag-nameEdit").val(data.data.flagName);
                $("#form-enterpriseEdit").val(data.data.entId);
                $("#form-remarkEdit").val(data.data.remark);
                $("#selected-color2").val(data.data.color);
                
                // 父窗体借用本页的编辑对话框
                var editDialog = window.top.window.borrowCustomModalDialog($("#edit-flag-form"));
                editDialog.modal({show:true, backdrop:'static'});
                flagTable.draw();
            } else{
                window.top.window.showScoMessage('ok', data.msg);
            }
        },
        error:function(XMLHttpRequest, textStatus) {
            if (XMLHttpRequest.status == 500) {
                var result = eval("(" + XMLHttpRequest.responseText + ")");
                alert(result.errorObject.errorText);
            }
        }
    });
}

/**
 * 打开创建的对话框
 * @returns
 */
function newFlag() {
    $("#flagCreateForm")[0].reset();

    var editDialog = window.top.window.borrowCustomModalDialog($("#create-flag-form"));
    editDialog.modal({show:true, backdrop:'static'});
}

$('#colorpalette1').colorPalette()
          .on('selectColor', function(e) {
            $('#selected-color1').val(e.color);
          });

$('#colorpalette2').colorPalette()
.on('selectColor', function(e) {
  $('#selected-color2').val(e.color);
});